package com.hcb.tonguetiphealth.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.model.FileInfo;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.homepage.HomepagePersonalWidget;

public class HeadPortraitActivity extends AbstractActivity {

	private String fileName = "";
	private ImageView img;
	private ListView dialogListView;
	private TextView tvUpload;
	private FileInfo fileInfo;
	private String userId;
	private Handler mHandler;
	private Activity ctx;
	private boolean uploadSuccess;
	private LinearLayout llBack;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.head_portrait);
		new BottomWidget(this);
		ctx = this;
		userId = getIntent().getStringExtra("userId");
		bindView();
		bindEvent();
		showSelectDialog();
	}

	private void bindView() {
		img = (ImageView)findViewById(R.id.img);
		tvUpload = (TextView)findViewById(R.id.homepage_headportrait_upload);
		llBack = (LinearLayout)findViewById(R.id.head_portrait_back);
	}

	private void bindEvent() {
		tvUpload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(fileInfo == null || fileInfo.getUrl()==null){
					Toast.makeText(ctx, "请选择头像！", Toast.LENGTH_LONG).show();
					return;
				}
				uploadHeadPortrait();
			}
		});
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog("正在上传...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if (uploadSuccess) {
						Toast.makeText(ctx, "头像修改成功！", Toast.LENGTH_LONG).show();
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else {
						Toast.makeText(ctx, "上传失败，请稍后重试！", Toast.LENGTH_LONG).show();
					}
					dismissMessageDialog();
					ctx.setContentView(new HomepagePersonalWidget(ctx));
					break;
				}
			}
		};
		llBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ctx.setContentView(new HomepagePersonalWidget(ctx));
			}
		});
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	private void uploadHeadPortrait(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		uploadSuccess = false;
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("userId", userId));
				List<FileInfo>fileList = new ArrayList<FileInfo>();
				fileList.add(fileInfo);
				//String response = HttpUtils.Post(Global.getServletheadportrait(), params, fileList);
				System.out.println("fileinfo"+fileInfo.getUrl());
				String response = HttpUtils.PostFile(Global.getServletheadportrait(), params, fileInfo);
				if (Global.DEBUG) {
					System.out.println("上传图片返回信息："+response);
				}
				if (response!=null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strReturn = jsonObject.getString("return");
						System.out.println("上传图片msg"+jsonObject.getString("msg"));
						if ("true".equals(strReturn)) {
							uploadSuccess = true;
							Global.user.setImgUrl(jsonObject.getString("img"));
						}else {
							uploadSuccess = false;
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						uploadSuccess = false;
					}
				}else {
					uploadSuccess = false;
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	
	private void startCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File fileDir1 = this.getFilesDir();
		String path = fileDir1.getParent() + File.separator + "tempPic";
		File fileDir2 = new File(path);
		if (!fileDir2.exists()) {
			fileDir2.mkdir();			
		}
		String  strName  =  "IMG_svenke.jpg";  
		
		//指定调用相机拍照后的照片存储路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), strName)));
		this.startActivityForResult(intent, 1);
	}

	private void startLocalFiles(){
		Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, 2);
	}
	
	public void showSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this); 
        final AlertDialog dialog = builder.create(); 
        /*builder.setPositiveButton("确定",null);    
        builder.setNegativeButton("取消",null); */  
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        
        LayoutInflater li = LayoutInflater.from(this); 
        View view = li.inflate(R.layout.res_book_dialog_list, null); 
   
        dialog.setView(view);
        dialogListView = (ListView)view.findViewById(R.id.selection_listview);
        List<String>selectList = new ArrayList<String>();
    	selectList.add("拍照");
		selectList.add("从本地相册");
		SelectionListAdapter adapter = new SelectionListAdapter(this,
				selectList);
		dialogListView.setAdapter(adapter);
        dialogListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				switch (arg2) {
				case 0:
					startCamera();
					break;
				case 1:
					startLocalFiles();
					break;
				default:
					break;
				}
				dialog.cancel();
			}
		});
        
        dialog.show(); 
    }

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				Toast.makeText(this, "请插入SD卡", Toast.LENGTH_LONG).show();
				return;
			}
			System.out.println("`````````````````==============");
			File fileDir1 = this.getFilesDir();
			String path = Environment.getExternalStorageDirectory()
					+ File.separator +"IMG_svenke.jpg";
			File tmp = new File(path);
			startPhotoZoom(Uri.fromFile(tmp));
//			FileOutputStream b = null;
//			File fileDir1 = this.getFilesDir();
//			String path = fileDir1.getParent() + File.separator + "tempPic"
//					+ File.separator;
//			File fileDir2 = new File(path);
//			fileDir2.mkdir();
//			
//			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
//			Date  curDate  =  new   Date(System.currentTimeMillis());//获取当前时间     
//			String  strName  =  "IMG_" + formatter.format(curDate) + ".jpg";  
//			
//			fileName = path + strName;
//			System.out.println("fileName:" + fileName);
//			try {
//				b = new FileOutputStream(fileName);
//				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					b.flush();
//					b.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			System.out.println("图片保存");
//			setImgBg(fileName);
			// ((ImageView)
			// findViewById(R.id.imageView)).setImageBitmap(bitmap);//
		} else if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
			Uri uri = data.getData();
			startPhotoZoom(uri);
//			if (uri.toString().contains("file")) {
//				//已经是绝对路径，从文件管理器传过来
//				fileName = uri.getPath();
//			} else {
//				//http://www.cnblogs.com/lingyun1120/archive/2012/04/18/2455212.html
//				//由从URI获得文件路径
//				//从图片库传过来
//				String[] proj = { MediaStore.Images.Media.DATA };
//				Cursor actualimagecursor = this.managedQuery(uri, proj,
//						null, null, null);
//				int actual_image_column_index = actualimagecursor
//						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//				actualimagecursor.moveToFirst();
//				String img_path = actualimagecursor
//						.getString(actual_image_column_index);
//				fileName = img_path;
//			}
//			String strName = fileName.substring(fileName.lastIndexOf("/")+1);
//			setImgBg(fileName);
		}else if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
			setPicToView(data);
//			setImgBg(fileName);
		}else {
			ctx.setContentView(new HomepagePersonalWidget(ctx));
		}
	}
	
	
	/**
	 * 裁剪图片方法实现
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri){
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		//下面这个crop=true是设置在开启的intent中设置显示的View可裁剪
		intent.putExtra("crop", "true");
		//aspecX aspectY是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		//outputX outputY是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}
	
	/**
	 * 保存裁剪之后的图片数据
	 * @param picData
	 */
	private void setPicToView(Intent picData){
		Bundle extras = picData.getExtras();
		if (extras != null) {
			Bitmap bitmap = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(bitmap);
			img.setBackgroundDrawable(drawable);
			
			FileOutputStream b = null;

			String path = Environment.getExternalStorageDirectory() + File.separator + "TongueTipHealth" + 
						  File.separator + "tempPic"
						  + File.separator;
			
			File fileDir2 = new File(path);
			fileDir2.mkdir();
			
			String  strName  =  "IMG_tmp.jpg";  
			
			fileName = path + strName;
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			fileInfo = new FileInfo();
			fileInfo.setName("spic");
			fileInfo.setUrl(fileName);
		}
	}
	
}